<template>
  <div style="width: 100%">
    <div v-show="disabled">{{valueDisplay}}</div>
    <t-select
      v-model="valueThis"
      value-type="object"
      :filterable="true"
      placeholder="请选择"
      :loading="loading"
      @focus="_focus"
      @popup-visible-change="_onPopupVisibleChange"
      :filter="_filter"
      :popupProps="cpPopupProps"
      :valueDisplay="valueDisplay"
      @change="_change"
      class="custom_select_input"
      v-show="!disabled"
      ref="controlInst"
    >
      <!-- 自定义底部内容 -->
      <div slot="panelTopContent" class="select-panel-footer" style="    text-align: right;padding-right: 10px; zoom: 86%; padding-left: 15px;">
        <small>支持名称和拼音检索</small>
        <customButton  title="刷新" theme="primary" size="small"  @click="getData(true)" style="padding: 5px; margin-left: 10px;"
                       :disabled="loading"

        />
      </div>
      <t-option v-for="item in cpOptions" :value="item.value" :label="item.label" :key="item.value">
        <div> {{ item.label }} </div>
      </t-option>
    </t-select>
  </div>
</template>

<script>

import utilVuex from '@/util/utilVuex'

export default {
  desc: '基础选择',
  name: 'parentSelect',
  props: {
    /**
     * @Description：选中值
     */
    value: {
      type: String,
      default: () => null
    },
    /**
     * @Description：显示名称
     */
    valueDisplay: {
      type: String,
      default: () => ''
    },
    /**
     * @Description：true: 禁用
     */
    disabled: {
      type: Boolean,
      default: () => false
    },
    /**
     * @Description：查询地址
     */
    getUrl: {
      type: String,
      default: () => ''
    },
    /**
     * @Description：查询条件
     */
    getQuery: {
      type: Function,
      default: () => {
        return null
      }
    },
    /**
     * @Description：数据过滤方法
     */
    dataFilter: {
      type: Function,
      default: () => {
        return null
      }
    },
    /**
     * @Description：选项宽度
     */
    popWidth: {
      type: Number,
      default: () => {
        return null
      }
    },
    /**
     * @Description：true 从状态管理获取数据
     */
    isVuex: {
      type: Boolean,
      default:  () => false
    },
    /**
     * @Description：vuex状态管理类型，对应getMap的key
     */
    vuexType: {
      type: String,
      default:  () => ''
    },
    /**
     * @Description：vuex状态管理数据标识，如 state.warehouseListByUser 的 warehouseListByUser
     */
    vuexGetKey: {
      type: String,
      default:  () => ''
    },
    /**
     * @Description：值字段名称
     */
    keyValue: {
      type: String,
      default:  () => 'id'
    },
    /**
     * @Description：标签字段名称
     */
    keyLabel: {
      type: String,
      default:  () => 'name'
    },
  },
  watch: {
    // 监听表单设置本组件的值
    value: {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler() {
        this.valueThis = this.value
      },
    },
  },
  data() {
    return {
      options: [],
      loading: false,
      timeLast: null,
      // 定义下拉宽度始终与触发浮层的元素（即select组件）等宽
      valueThis: '',
      valueSearch: '',
    }
  },
  computed: {
    cpPopupProps() {
      let prop = {
        overlayInnerStyle: (trigger) => ({ width: `${trigger.offsetWidth}px` }),
        overlayClassName: 'custom_select__overlay_option'
      }
      if (this.popWidth != null) {
        prop.overlayInnerStyle = (trigger) => ({ width: `${this.popWidth}px` })
      }
      return prop
    },
    cpOptions() {
      if (this.strings.isBlank(this.valueSearch)) {
        return this.options
      }
      return this.options.filter(option => {
        return option.label.toLowerCase().indexOf(this.valueSearch) != -1
          || this.pyutils.getAllFirstLetter(option.label).toLowerCase().indexOf(this.valueSearch) != -1
          || this.pyutils.chineseToPinYin(option.label).toLowerCase().indexOf(this.valueSearch) != -1
      })
    }
  },
  methods: {
    _filter(search, option) {
      let searchL = search.toLowerCase()
      this.valueSearch = searchL
      return option.label.toLowerCase().indexOf(searchL) != -1
        || this.pyutils.getAllFirstLetter(option.label).toLowerCase().indexOf(searchL) != -1
        || this.pyutils.chineseToPinYin(option.label).toLowerCase().indexOf(searchL) != -1
    },

    _focus() {
      this.getData(false)
    },

    _onPopupVisibleChange(isShow) {
      if (!isShow) {
        setTimeout(() => {
          this.valueSearch = ''
        }, 1000)
      }
    },

    focus() {
      this.$refs.controlInst.setInnerPopupVisible(true)
      $(this.$refs.controlInst.$el).find('.t-input__inner').focus()
    },

    _change(param) {
      let selectItemIndex = this.options.findIndex((tmp) => tmp[this.keyValue] == param.value)
      let selectItem = null
      if (selectItemIndex != -1) {
        selectItem = this.options[selectItemIndex]
        console.log('parentSelect', selectItem)
        this.$emit('change',  selectItem)
      }
    },
    // 加载数据
    getData(isByUser = false) {
      if (this.isVuex) {
        return this.getDataFromVuex(isByUser)
      }
      if (!isByUser && this.timeLast) {
        return
      }
      this.loading = true
      let wrapper = this.getQuery()
      if (wrapper == null) {
        wrapper = this.$newWrapper()
      }
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.$ajax.get(this.getUrl, {params}).then((resp) => {
        if (resp.code == 0) {
          this.options = resp.data.map(item => {
            item.value = item[this.keyValue]
            item.label = item[this.keyLabel]
            return item
          })
          this.timeLast = this.dates.getCurrentDate(this.dates.defaultDateTimePattern)
        }
        if (isByUser) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else{
          this.loading = false
        }
      }).catch(e => {
        this.loading = false
      })
    },

    // 从状态管理获取数据
    getDataFromVuex(isByUser = false) {
      // 重新刷新数据
      if (isByUser) {
        this.loading = true
        this.utilVuex.syncAll(this, () => {
          setTimeout(() => {
            this.loading = false
            this.getDataFromVuex(false)
          }, 500)
        }, [this.vuexType])
        return
      }
      let list = global.vue.$store.getters[this.vuexGetKey] || []
      this.options = list.map(item => {
        item.value = item[this.keyValue]
        item.label = item[this.keyLabel]
        item.name = item[this.keyLabel]
        return item
      })

      if (this.dataFilter && this.options.length > 0) {
        this.options = this.dataFilter(this.options)
      }
    }
  },
}
</script>

<style lang="scss">
.custom_select__overlay_option {
  .t-popup__content{
    width: 230px;
    max-height: 400px;
  }
  .t-select-option{
    overflow: hidden; /*溢出隐藏*/
    text-overflow: ellipsis; /*以省略号...显示*/
    white-space: nowrap; /*强制不换行*/
  }
  .t-select__list{
    max-height: 300px;
    overflow: auto;
  }
}
.custom_select_input{
  .t-input--focused .t-input__prefix{
    display: none !important;
  }
  .t-input__prefix{
    width: 100%; /*必须设置宽度*/
    overflow: hidden; /*溢出隐藏*/
    text-overflow: ellipsis; /*以省略号...显示*/
    white-space: nowrap; /*强制不换行*/
  }
  .t-input__prefix:empty{
    display: none !important;
  }
}
</style>
